package com.glsc.ngateway.common.base.exception;

import lombok.*;
import org.apache.logging.log4j.util.Strings;

/**
 * 功能描述: <br>
 *
 * @author gaojc
 * @date 2020/9/1 13:34
 */
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class PlatformException extends RuntimeException {
    private int status;
    private String msg;
    private Throwable throwable;
    /**
     * 是否打印堆栈信息，供web异常拦截器捕获判断，默认打印
     * {@link WebExceptionHandler#platformExceptionHandler}
     */
    private boolean printStackTraceFlag = true;

    /**
     * 是否发送错误邮件至管理员
     * {@link WebExceptionHandler#platformExceptionHandler}
     */
    private boolean sendMail2Admin = true;

    /**
     * 兼容父类Message和子类msg
     * @return
     */
    public String getMsg(){
        return Strings.isNotBlank(this.msg) ? this.msg : this.getMessage();
    }

    public PlatformException(int status, String msg, Throwable throwable) {
        this.status = status;
        this.msg = msg;
        this.throwable = throwable;
    }

    public static PlatformException error(String msg) {
        return new PlatformException(-1, msg, null);
    }

    public static PlatformException errorWithOutMail(String msg) {
        PlatformException e = new PlatformException(-1, msg, null);
        e.setPrintStackTraceFlag(false);
        e.setSendMail2Admin(false);
        return e;
    }

    public static PlatformException error(String msg, Boolean printStackTraceFlag) {
        return new PlatformException(-1, msg, null, printStackTraceFlag, true);
    }


    public static PlatformException error(String msg, Boolean printStackTraceFlag, Boolean sendMail2AdminFlag) {
        return new PlatformException(-1, msg, null, printStackTraceFlag, sendMail2AdminFlag);
    }

    @Override
    public String toString() {
        return "PlatformException{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", throwable=" + throwable +
                '}';
    }
}
